<template>
    <div class="upload-view" @click="selectFile">
        <img class="upload-svg" :src="uploadImg ? uploadImg : uploadSvg">
    </div>
</template>

<script setup>
import { defineEmits, ref } from 'vue';
import uploadSvg from './svg/upload.svg'
import { uploadImage, saveImageUrl } from '../api/image'
const emits = defineEmits(['getImageUrl']);
let uploadImg = ref('')


const selectFile = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.multiple = true;
    input.onchange = (e) => {
        const files = e.target.files;
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = () => {
                const canvas = document.createElement('canvas');
                canvas.width = img.width;
                canvas.height = img.height;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0);
                const dataURL = canvas.toDataURL('image/jpeg', 0.8);
                const blob = dataURLToBlob(dataURL);
                const formData = new FormData();
                formData.append('file', blob, 'image.jpg');
                uploadImage(formData).then(res=> {
                    if (res.code === 200) {
                        // 调用父组件的getImageUrl修改父组件中imageUrl
                        console.log(res)
                        uploadImg.value = res.data.fileUrl;
                        emits('getImageUrl', res.data.fileUrl);
                        const params = {
                            name: '测试图片',
                            image: res.data.fileUrl,
                        }
                        saveImageUrl(params).then(res=> {
                            if (res.code === 200) {
                                alert('保存图片地址成功');
                            } else {
                                alert('保存图片地址失败');
                            }
                        })
                    } else {
                        alert('上传失败');
                    }
                })
            };
        };
        reader.readAsDataURL(files[0]);
    };
    input.click();
}

const dataURLToBlob = (dataURL) => {
    const arr = dataURL.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
</script>

<style scoped>
.upload-view {
    width: 100%;
    padding: 10px;
    background: #fff;
    box-sizing: border-box;
    border: 1px dashed #ccc;
    border-radius: 12px;
}
.upload-svg {
    width: 100%;
}
</style>